package com.tf.temper.controller;

import com.ccssoft.m8.common.ccssoft.modules.util.EntityWrapperHandle;
import com.ccssoft.m8.common.web.BaseController;
import com.tf.temper.entity.*;
import com.tf.temper.service.AdmininfoService;
import com.tf.temper.service.DeviceService;
import com.xiaoleilu.hutool.codec.Base64;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 用户登录相关
 * @author allen
 * @date: 2020年9月14日上午10:56:20
 */
@Api(value = "用户登录相关",description="LoginController")
@RestController
public class LoginController extends BaseController
{
    private static boolean  mbinit = false;
    private static HashMap<String,String> mDevonlien = new  HashMap<String,String>();
    private final CacheManager singletonManager = CacheManager.create();
    @Autowired
    private AdmininfoService<AdmininfoEntity> admininfoService;
    @Autowired
    private DeviceService<DeviceEntity> deviceService;
    @ApiOperation("用户登录接口")
    @PostMapping("/loginin")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public LoginReturnEntity<String> login(@RequestBody LoginupEntity user)
    {
        if(user!=null)
        {
            EntityWrapperHandle<AdmininfoEntity> ew = new EntityWrapperHandle<AdmininfoEntity>();
            ew.eq("username", user.getName());
            ew.eq("password", user.getPassword());
            List<AdmininfoEntity> userlist =  admininfoService.selectList(ew);
            String token = "";
            if(null !=userlist&&userlist.size()>0)
            {
                token = Base64.encode(getUUIDPrimaryKey()+"-"+userlist.get(0).getId().toString());
                Cache memoryOnlyCache = new Cache(token,5000, false, false, 18000,3000);
                singletonManager.addCache(memoryOnlyCache);
                return new LoginReturnEntity<String>().ok(token);
            }
            else
            {
                return new LoginReturnEntity<String>().error("用户不存在或者密码错误");
            }
        }
        return new LoginReturnEntity<String>().error("user or pwd is null");
    }
    /**
     * 修改密码
     */
    @ApiOperation("用户修改密码接口")
    @PutMapping("/password")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public LoginReturnEntity<String> modifypwd(@RequestBody CpwdEntity user)
    {
        if(user!=null)
        {
            EntityWrapperHandle<AdmininfoEntity> ew = new EntityWrapperHandle<AdmininfoEntity>();
            ew.eq("username", user.getName());
            ew.eq("password", user.getOldPassword());
            List<AdmininfoEntity> userlist =  admininfoService.selectList(ew);
            if(null !=userlist&&userlist.size()>0)
            {
                if(user.getNewPassword()!=null&&user.getNewPassword().equals("")==false)
                {
                    AdmininfoEntity oldenty =  userlist.get(0);
                    oldenty.setPassword(user.getNewPassword());
                    admininfoService.updateById(oldenty);
                    return new LoginReturnEntity<String>().ok("");
                }
               else
               {
                    return new LoginReturnEntity<String>().error("new password is null");
               }
            }
            else
            {
                return new LoginReturnEntity<String>().error("modify fail");
            }
        }
        return new LoginReturnEntity<String>().error("user or pwd is null");
    }
    //设置mDevonlien的值
    public static void setmDevonlien(String key,String val)
    {
       if(key!=null&&key.equals("")==false&&val!=null&&val.equals("")==false)
       {
           mDevonlien.put(key,val);
       }
    }
    @ApiOperation("登录设备接口")
    @GetMapping("/logindevice/keep")
    @CrossOrigin(origins = "*",maxAge = 86400)
    public  String logindevicekeep()
    {
        if(mbinit==true)
        {
            return "ok";
        }
        EntityWrapperHandle<DeviceEntity> ew = new EntityWrapperHandle<DeviceEntity>();
        List<DeviceEntity> devinfo  =  deviceService.selectList(ew);
        if(devinfo!=null&&devinfo.size()>0)
        {
            for (int i = 0;i<devinfo.size();++i)
            {
                DeviceEntity  dinfo = devinfo.get(i);
                if(dinfo.getOnline()==1)
                {
                    mDevonlien.put(dinfo.getDeviceid(),3+"");
                }
            }
        }
        new Thread(() ->
        {
            while (true)
            {
                try
                {
                    Thread.sleep(60 * 1000);
                    Iterator it = mDevonlien.keySet().iterator();
                    while (it.hasNext())
                    {
                        String  key = (String) it.next();
                        String  value = (String) mDevonlien.get(key);
                        int count = Integer.valueOf(value);
                        count = count - 1;
                        if(count<=0)
                        {
                            EntityWrapperHandle<DeviceEntity> ewupdate = new EntityWrapperHandle<DeviceEntity>();
                            mDevonlien.remove(key);
                            ewupdate.eq("deviceid", key);
                            DeviceEntity newdeventity = new DeviceEntity();
                            newdeventity.setDeviceid(key);
                            newdeventity.setOnline(0);
                            deviceService.update(newdeventity,ewupdate);
                        }
                        else
                        {
                            mDevonlien.put(key,count+"");
                        }
                    }
                }
                catch (Exception e)
                {

                }
            }
        }).start();
        mbinit = true;
        return "init ok";
    }
}